<template>
  <el-dialog
    class="add-bim-modal"
    :title="title"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :visible="visible"
    :width="$setRem(900)"
    :before-close="handleCancel">
    <div class="form-container">
      <el-form
        :model="ruleForm"
        :rules="rules"
        size="medium"
        ref="ruleForm"
        class="rule-form"
        :label-width="$setRem(140)"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              class="tree-form"
              label="专业名称"
              prop="majorId">
              <el-input
                placeholder="请选择专业名称"
                :disabled="hasDisable"
                v-model.trim="ruleForm.majorName"
                @focus="handleFocus"
                @input="handleInput"
                @blur="handleBlur">
              </el-input>
              <el-tree
                v-show="hasShow"
                class="menu-filter-tree"
                ref="tree"
                highlight-current
                :current-node-key="ruleForm.majorId"
                :data="menus"
                :props="defaultProps"
                :disabled="hasDisable"
                node-key="id"
                default-expand-all
                @node-click="handleClick"
                :filter-node-method="filterNode">
              </el-tree>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模型名称" prop="fileName" required>
              <el-input
                placeholder="请输入模型名称"
                :disabled="hasDisable"
                v-model="ruleForm.fileName"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="图模联动" prop="fileType">
              <el-radio-group class="linkage" :disabled="hasDisable" v-model="ruleForm.fileType">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="ruleForm.fileType === '1'" :span="12">
            <el-form-item label="图纸ID" prop="drawId" required>
              <el-input :disabled="hasDisable" v-model="ruleForm.drawId" placeholder="请输入联动图纸ID"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="附件" prop="file" required>
            <div class="file-list" v-if="hasDisable">
              <div class="file-text">
                <span
                  class="file-name"
                  :title="options.fileName">
                  {{ options.fileName || '' }}
                </span>
              </div>
            </div>
            <div class="file-list" v-else-if="ruleForm.file">
              <div class="file-text">
                <span
                  class="file-name"
                  :title="ruleForm.file.name">
                  {{ ruleForm.file.name }}
                </span>
                <i v-if="!hasDisable" class="el-icon-delete file-delete" @click="handleRemove"></i>
              </div>
            </div>
            <el-upload
              v-else
              ref="upload"
              :limit="1"
              action="#"
              accept=".rvt,.rfa,.dwg,.dxf,.skp,.ifc,.dgn,.obj,.stl,.3ds,.dae,.ply,.igms,.gtj"
              :multiple="false"
              :on-change="handleChange"
              :file-list="[]"
              :show-file-list="false"
              :disabled="hasDisable"
              :auto-upload="false">
              <el-button
                slot="trigger"
                :disabled="hasDisable"
                :loading="fileLoading"
                size="small"
                icon="el-icon-upload2"
                type="primary">
                选取文件
              </el-button>
            </el-upload>
          </el-form-item>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="抄送人" prop="cUser">
              <el-select
                placeholder="请选择抄送人"
                clearable
                filterable
                multiple
                :disabled="hasDisable"
                v-model="ruleForm.cUser">
                <el-option
                  v-for="v in userList"
                  :label="v.userName"
                  :value="v.uuid"
                  :key="v.uuid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <span class="dialog-footer" slot="footer">
      <el-button type="primary" @click="handleCancel">取 消</el-button>
      <el-button
        v-if="!hasDisable"
        class="success"
        type="primary"
        :loading="loading"
        @click="hanldeSave">
        提 交
      </el-button>
    </span>
  </el-dialog>
</template>

<script>

export default {
  props: {
    // 弹框是否展示
    visible: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    options: {
      type: Object,
      default: () => ({})
    },
    // 检查区域
    menus: {
      type: Array,
      default: () => []
    },
    title: {
      type: String,
      default: '模型管理'
    },
    type: {
      type: String,
      default: 'add'
    },
  },
  data() {
    return {
      userList: [],
      activeData: {},
      hasShow: false,
      defaultProps: {
        children: 'children',
        label: 'majorName'
      },
      fileLoading: false,
      ruleForm: {
        id: '',
        majorId: '',
        majorName: '',
        fileName: '',
        fileType: '0',
        file: null,
        cUser: [],
        drawId: ''
      },
      rules: {
        file: [
          { required: true, message: '请上传模型' }
        ],
        fileName: [
          { required: true, message: '请输入图纸名称' }
        ],
        drawId: [
          { required: true, message: '请输入联动图纸ID' }
        ],
      },
    };
  },
  computed: {
    hasDisable() {
      return this.type === 'detail';
    },
    userId() {
      return this.$store.state.userInfo.uuid;
    },
    projectName() {
      return this.$store.state.currentProjectInfo.projectName;
    },
    projectId() {
      return this.$store.state.currentProjectId;
    },
    // 文件后缀
    fileType() {
      const { file } = this.ruleForm;
      if (!file) return;
      const list = file.name && file.name.match(/\..*$/);
      return list ? list[0] : '';
    },
  },
  watch: {
    // 监听回填数据
    options: {
      deep: true,
      handler: function (data) {
        if (this.$checkType(data) === 'object' && Object.keys(data).length) {
          const { majorId } = data;
          const keys = Object.keys(this.ruleForm);
          keys.forEach(key => {
            const value = data[key] || '';
            if (key === 'majorName' && majorId && majorId !== '0') {
              this.$nextTick(() => {
                const { data } = this.$refs.tree.getNode(majorId) || {};
                if (data) {
                  this.ruleForm[key] = data.majorName;
                  this.activeData = data || {};
                  this.$refs.tree.setCurrentKey(majorId , true);
                }
              });
              return;
            }
            if (key === 'cUser') {
              this.ruleForm[key] = data.cUser
                ? data.cUser.split(',')
                : [];
              return;
            }
            this.ruleForm[key] = value;
          });
        }
      }
    },
    // 监听弹框显示/隐藏
    visible(data) {
      if (!data) {
        Object.keys(this.ruleForm).forEach(key => {
          if (key === 'cUser') {
            this.ruleForm[key] = [];
            return;
          }
          if (key === 'fileType') {
            this.ruleForm[key] = '0';
            return;
          }
          if (key === 'file') {
            this.ruleForm[key] = null;
            return;
          }
          this.ruleForm[key] = '';
        });
      }
    }
  },
  created() {
    this.getUserList();
  },
  methods: {
    /**
       * 获取用户列表数据
       */
    async getUserList() {
      const params = {
        pageNum: 1,
        id: this.projectId,
        pageSize: 1000,
        type: '1' // 1：已选择用户；2：未选择用户
      };
      const { success, data: {
        data
      }} = await this.$Model.getProjectUserList(params);
      if (success && data) {
        this.userList = data.list || [];
      }
    },
    // 点击菜单节点
    handleClick(data, node, ref) {
      const { id, majorName } = data;
      this.ruleForm.majorId = id;
      this.activeData = data;
      this.ruleForm.majorName = majorName;
      this.hasShow = false;
    },
    handleInput(val) {
      this.$refs.tree && this.$refs.tree.filter(val);
    },
    handleFocus() {
      this.hasShow = true;
    },
    handleBlur(e) {
      const className = e.relatedTarget && e.relatedTarget.className;
      this.hasShow = className && /el-tree/g.test(className);
      if (this.ruleForm.majorName !== this.activeData.majorName) {
        this.ruleForm.majorName = this.activeData.majorName || '';
        this.$refs.tree && this.$refs.tree.filter('');
      }
    },
    // 过滤节点
    filterNode(value, data) {
      if (!value) return true;
      return data.majorName.indexOf(value) !== -1;
    },
    // 上传文件
    handleChange(file) {
      this.ruleForm.file = file.raw;
      if (!this.ruleForm.fileName) {
        this.ruleForm.fileName = file.name.replace(/\..*$/, '');
      }
      return false;
    },
    // 下载文件
    handleUpload(fileUrl) {
      fileUrl && window.open(this.$checkUrl(fileUrl));
    },
    // 删除文件
    handleRemove() {
      this.ruleForm.file = null;
    },
    hanldeSave() {
      if (this.hasDisable) return;
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const {
            cUser,
            createrUser,
            file,
            fileName,
            ...others
          } = this.ruleForm;
          delete others.majorName;
          // const newFile = new window.File([file], fileName + this.fileType, {
          //   type: file.type
          // });
          this.$emit('submit', {
            ...others,
            fileName,
            file,
            projectName: this.projectName,
            moduleType: '1', // 1：bim模型；2：全景模型；3：倾斜模型)
            cUser: cUser.join(','),
            createrUser: createrUser || this.userId,
          });
        }
      });
    },
    // 取消
    handleCancel() {
      this.$emit('cancel');
    }
  },
};
</script>

<style lang="scss" scoped>
  @import "../../../assets/styles/dialog";
  .add-bim-modal {
    .form-container {
      width: 100%;
      padding: 20px 20px 20px 0;
      /deep/ .el-form-item {
        .tip {
          margin-left: 20px;
        }
      }
      .tree-form {
        /deep/ .el-form-item__content {
          position: relative;
          .menu-filter-tree {
            position: absolute;
            top: 38px;
            left: 1px;
            width: 100%;
            max-height: 300px;
            z-index: 2;
            background-color: #fff;
            border: 1px solid #f1f1f1;
            border-top-color: transparent;
            box-shadow: 0 2px 8px 0 #bbb;
            border-radius: 4px;
            overflow: auto;
          }
        }
      }
      .file-list {
        width: 100%;
        max-height: 120px;
        overflow-y: auto;
        .file-text {
          width: 100%;
          display: flex;
          align-items: center;
          cursor: pointer;
          transition: color .2s;
          .file-name {
            max-width: calc(100% - 100px);
            display: inline-block;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            padding-right: 20px;
          }
          &:hover {
            color: $mainColor;
          }
        }
      }
      .el-checkbox {
        color: #fff;
      }
    }
  }
</style>
